<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <!-- 左侧题目区域 -->
      <a-col :md="12" :xs="24">
        <a-card class="question-card" :bordered="true">
          <template #title>
            <a-tabs :active-key="activeTab" @change="handleTabChange">
              <a-tab-pane key="question" title="题目详情">
                <template #icon><icon-file /></template>
              </a-tab-pane>
              <a-tab-pane key="comment" title="评论区">
                <template #icon><icon-message /></template>
              </a-tab-pane>
              <a-tab-pane key="answer" title="参考答案">
                <template #icon><icon-bulb /></template>
              </a-tab-pane>
            </a-tabs>
          </template>

          <!-- 题目详情内容 -->
          <div
            v-if="activeTab === 'question' && question"
            class="question-content"
          >
            <!-- 判题条件卡片 -->
            <a-card class="judge-conditions-card" :bordered="false">
              <template #title>
                <div class="section-title">
                  <icon-settings />
                  <span>判题条件</span>
                </div>
              </template>
              <a-row :gutter="16">
                <a-col :span="8">
                  <div class="condition-item">
                    <div class="condition-label">时间限制</div>
                    <div class="condition-value">
                      {{ question.judgeConfig?.timeLimit ?? 0 }} ms
                    </div>
                  </div>
                </a-col>
                <a-col :span="8">
                  <div class="condition-item">
                    <div class="condition-label">内存限制</div>
                    <div class="condition-value">
                      {{ question.judgeConfig?.memoryLimit ?? 0 }} KB
                    </div>
                  </div>
                </a-col>
                <a-col :span="8">
                  <div class="condition-item">
                    <div class="condition-label">堆栈限制</div>
                    <div class="condition-value">
                      {{ question.judgeConfig?.stackLimit ?? 0 }} KB
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-card>

            <!-- 题目内容 -->
            <div class="markdown-content">
              <MdViewer :value="question.content || ''" />
            </div>
          </div>

          <!-- 评论区内容 -->
          <div v-if="activeTab === 'comment'" class="comments-content">
            <UserComment :questionId="questionId" />
          </div>

          <!-- 答案内容 -->
          <div v-if="activeTab === 'answer'" class="answer-content">
            <QuestionAnswer :question="question" />
          </div>
        </a-card>
      </a-col>

      <!-- 右侧代码编辑区域 -->
      <a-col :md="12" :xs="24">
        <a-card class="code-card" :bordered="true">
          <template #title>
            <div class="card-title">
              <icon-code />
              <span>代码编辑器</span>
            </div>
          </template>

          <!-- 语言选择 -->
          <div class="language-selector">
            <a-select
              v-model="form.language"
              style="width: 100%"
              placeholder="选择编程语言"
              allow-clear
            >
              <a-option>Java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
              <a-option>SQL</a-option>
              <a-option>shell</a-option>
            </a-select>
          </div>

          <!-- 代码编辑器 -->
          <div class="code-editor-container">
            <CodeEditor
              :value="form.code as string"
              :language="form.language"
              :handle-change="changeCode"
            />
          </div>

          <!-- 提交按钮 -->
          <div class="submit-actions">
            <a-space>
              <a-button @click="resetCode" type="outline">
                <template #icon><icon-refresh /></template>
                重置代码
              </a-button>
              <a-button type="primary" @click="doSubmit" :loading="submitting">
                <template #icon><icon-send /></template>
                提交代码
              </a-button>
            </a-space>
          </div>
        </a-card>

        <!-- 显示测试用例 -->
        <a-card
          v-if="question?.judgeCase"
          class="test-cases-card"
          :bordered="true"
        >
          <template #title>
            <div class="card-title">
              <icon-experiment />
              <span>测试用例</span>
            </div>
          </template>

          <a-collapse accordion>
            <a-collapse-item
              v-for="(testCase, index) in parseTestCases(question.judgeCase)"
              :key="index"
              :header="`测试用例 ${index + 1}`"
            >
              <div class="test-case-content">
                <div class="test-case-input">
                  <div class="test-case-label">输入:</div>
                  <pre class="test-case-data">{{ testCase.input }}</pre>
                </div>
                <div class="test-case-output">
                  <div class="test-case-label">期望输出:</div>
                  <pre class="test-case-data">{{ testCase.output }}</pre>
                </div>
              </div>
            </a-collapse-item>
          </a-collapse>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, withDefaults, defineProps, watchEffect } from "vue";
import UserComment from "@/components/UserComment.vue";
import QuestionAnswer from "@/components/QuestionAnswer.vue"; // 新增导入答案组件
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest,
  QuestionVO,
} from "../../../generated";
import { useRoute, useRouter } from "vue-router";

interface Props {
  id: string;
}
const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});
const question = ref<QuestionVO>();
const route = useRoute();
const router = useRouter();
const questionId = route.params.id;

// 从URL获取当前激活的标签页，如果没有则默认为"question"
const activeTab = ref((route.query.tab as string) || "question");

// 加载数据
const loadData = async () => {
  try {
    // 先获取基本信息（不包含 answer）
    const questionVoRes =
      await QuestionControllerService.getQuestionVoByIdUsingGet(props.id);
    if (questionVoRes.code !== 0) {
      message.error("加载失败：" + questionVoRes.message);
      return;
    }

    // 先赋值基本信息
    question.value = questionVoRes.data;
    console.log("基本信息（无 answer）：", question.value);

    // 再获取答案信息
    const questionAnswerRes =
      await QuestionControllerService.getQuestionByIdUsingGet(props.id);
    if (questionAnswerRes.code === 0) {
      // 只更新 answer，不覆盖其他数据
      question.value.answer = questionAnswerRes.data.answer;
      console.log("获取的 answer：", question.value.answer);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  }
};

// 处理标签页变化
const handleTabChange = (key: string) => {
  activeTab.value = key;
  // 更新URL查询参数，保留标签页状态
  router.replace({
    path: route.path,
    query: { ...route.query, tab: key },
  });
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: "",
});

watchEffect(() => {
  loadData();
});

const handleColor = (record: string): string => {
  if (record === "困难") {
    return "red";
  } else if (record === "中等") {
    return "orange";
  } else if (record === "简单") {
    return "green";
  } else {
    return "gray";
  }
};

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
    // 使用 window.location.href 跳转
    window.location.href = "/question_submit";
  } else {
    message.error("提交失败," + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const changeCode = (value: string) => {
  form.value.code = value;
};
</script>

<style scoped>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-title,
.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #165dff;
  font-weight: 500;
}

/* 题目区域样式 */
.question-card,
.code-card,
.test-cases-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.question-content,
.comments-content,
.answer-content {
  padding: 16px 0;
}

/* 判题条件卡片 */
.judge-conditions-card {
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.condition-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.condition-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.condition-value {
  font-size: 18px;
  font-weight: 600;
  color: #165dff;
}

/* 代码编辑器 */
.language-selector {
  margin-bottom: 16px;
}

.code-editor-container {
  margin-bottom: 16px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  overflow: hidden;
  height: 400px;
}

.submit-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 测试用例样式 */
.test-case-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.test-case-input,
.test-case-output {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
}

.test-case-label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}

.test-case-data {
  background-color: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  padding: 8px;
  margin: 0;
  font-family: "Courier New", monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

/* Markdown 内容样式 */
.markdown-content {
  padding: 16px;
  background-color: white;
  border-radius: 8px;
}

/* Tab 样式优化 */
:deep(.arco-tabs-header-title) {
  padding: 12px 16px;
}

:deep(.arco-tabs-header-title-active) {
  font-weight: 600;
}

:deep(.arco-tabs-content) {
  padding: 0;
}

/* 折叠面板样式 */
:deep(.arco-collapse-item-header) {
  background-color: #f5f7fa;
  font-weight: 500;
}

:deep(.arco-collapse-item) {
  margin-bottom: 8px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}
</style>
